package cn.bugDance.domain.strategy.service.rule.tree.impl;


import cn.bugDance.domain.strategy.model.entity.RuleTreeDetermineEntity;
import cn.bugDance.domain.strategy.model.entity.RuleTreeFactorEntity;
import cn.bugDance.domain.strategy.model.valobj.DetermineTypeVO;
import cn.bugDance.domain.strategy.model.valobj.StrategyConstant;
import cn.bugDance.domain.strategy.repository.IStrategyRepository;
import cn.bugDance.domain.strategy.service.rule.tree.AbstractRuleTree;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Component(StrategyConstant.StrategyRule.RULE_STOCK)
@Slf4j
public class RuleStockTree extends AbstractRuleTree {

    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public RuleTreeDetermineEntity action(RuleTreeFactorEntity ruleTreeFactorEntity) {

        log.info("【策略领域层-RuleStockTree】: 规则规则树引擎节点-库存锁执行, strategyId: {}, awardId: {}", ruleTreeFactorEntity.getStrategyId(), ruleTreeFactorEntity.getAwardId());

        Long strategyId = ruleTreeFactorEntity.getStrategyId();
        Integer awardId = ruleTreeFactorEntity.getAwardId();
        List<String> ruleModels = ruleTreeFactorEntity.getRuleModels();
        Date endDateTime = ruleTreeFactorEntity.getEndDateTime();

        if(!ruleModels.contains(StrategyConstant.StrategyRule.RULE_STOCK)){
            RuleTreeDetermineEntity ruleTreeDetermineEntity = new RuleTreeDetermineEntity();
            ruleTreeDetermineEntity.setDetermineTypeVO(DetermineTypeVO.ALLOW);
            ruleTreeDetermineEntity.setAwardId(awardId);
            return ruleTreeDetermineEntity;
        }

        boolean result = strategyRepository.strategyAwardSubtractionQuota(strategyId, awardId, endDateTime);
        if(!result){
            RuleTreeDetermineEntity ruleTreeDetermineEntity = new RuleTreeDetermineEntity();
            ruleTreeDetermineEntity.setDetermineTypeVO(DetermineTypeVO.TAKE_OVER);
            ruleTreeDetermineEntity.setAwardId(awardId);
            return ruleTreeDetermineEntity;
        }

        RuleTreeDetermineEntity ruleTreeDetermineEntity = new RuleTreeDetermineEntity();
        ruleTreeDetermineEntity.setDetermineTypeVO(DetermineTypeVO.ALLOW);
        ruleTreeDetermineEntity.setAwardId(awardId);
        return ruleTreeDetermineEntity;
    }
}
